<template>
  <div class="chat-container">
    <!-- 聊天 -->
    <div class="contAllThree mobilChat">
      <div :class="[{ mobileMode: isActive }]" class="menuBox marginRight flex flex-direction mobilTop mobil AllOne" :style="{ height: screenHeight + 'px' }">
        <technical-list @changeCot="changeCot" ref="ChList"></technical-list>
        <div class="closeMode" @click="isActive = false"><div class="closeBtn">关闭</div></div>
      </div>
      <!-- <div
        :class="[{ mobileMode: isActive }]"
        class="AllOne marginRight flex flex-direction mobil"
        :style="{ height: screenHeight + 'px' }"
      >
        <technical-list @changeCot="changeCot" ref="ChList"></technical-list>
      </div> -->
      <div class="flexReturn navMarginTop marginRight flex flex-direction">
        <div class="AllOne" style="border-radius: 20px">
          <div class="chat-content">
            <div class="chat" :style="{ height: screenHeight - 240 + 'px', overflow: 'hidden auto' }">
              <div class="classify left" v-show="bulletBox">
                <div class="chatBox">
                  <div class="chat-header">
                    <img :src="getAvatarTips()" />
                  </div>
                  <div class="messages bei-jin">
                    <div class="message">
                      <div class="message-text">{{ menuTitleData.tips }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <div ref="myElement" style="float: left; width: 100%" v-show="!bulletBox">
                <div
                  v-for="(message, index) in messages"
                  :key="index"
                  :id="'item-' + message.id"
                  :class="['classify', message.role === 'user' ? 'right base' : 'left']"
                  v-scroll
                >
                  <div class="chatBox">
                    <div class="chat-header">
                      <img
                        v-if="message.role === 'user'"
                        :src="
                          getAvatar() === undefined
                            ? 'https://cos.kuaijingai.com/upload/system_config_img/20230608/6481c9b19470895793.png'
                            : getAvatar()
                        "
                      />
                      <img v-else :src="getAvatarTips()" />
                      <div class="username"></div>
                    </div>
                    <div class="messages">
                      <div class="message">
                        <div
                          :class="['message-text', activeStep === message.id ? 'active' : '']"
                          v-if="message.content !== ''"
                          style="white-space: pre-wrap">{{ message.content }}<div class="execute" v-if="message.role !== 'user' && executeShow && messages.length - 1 === index">...<div class="loading"></div></div></div>
                        <div class="message-text" v-else>
                          正在加载中
                          <div class="loading"></div>
                        </div>
                        <!-- <div v-html="message.content"></div> -->
                      </div>
                    </div>
                    <div class="iconList" v-if="message.content !== ''">
                      <div class="iconDt" @click="copyText(message.content)">
                        <a-tooltip title="复制">
                          <a-button type="link" icon="copy" size="small" />
                        </a-tooltip>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="contAllThree histWk">
              <div class="mobileCont" ref="claims">
                <div class="AllOne" :class="[{ mobileContActive: isMobileCont }]">
                  <div class="newChatBtn" @click="openMobileMode" style="margin-top: 14px">查看技能模型</div>
                  <div class="historyTime">当前对话：{{ timeListStr }}</div>
                </div>
              </div>
            </div>

            <div class="inputSend">
              <!-- <div class="chatFunction">
              <button class="chat-atn middle pop" @click="handleAdd">
                <i class="iconfont icon-lightning"></i>
                提示器
              </button>
              <button class="chat-atn middle pop" @click="handleAdd1">
                <i class="iconfont icon-lightning"></i>
                对话记录
              </button>
              <div class="fixBoom" @click="StopGeneration" v-if="!textareaShow">停止生成</div>
            </div> -->
              <!-- 发送 -->
              <div class="chat-messages">
                <!-- <input
        class="chat-input"
        :disabled="!textareaShow"
        v-model="newMessage"
        @keyup.enter="sendMessage"
        placeholder="请输入内容..."
      /> -->
                <textarea
                  class="chat-input"
                  placeholder="请输入内容..."
                  :disabled="!textareaShow"
                  v-model="newMessage"
                ></textarea>
                <button
                  :class="['chat-atn', isInputEmpty ? 'disable' : 'active']"
                  @click="sendMessage"
                  :disable="isInputEmpty"
                >
                  发送
                </button>
                <a-popconfirm title="确定删除该对话内容吗?" @confirm="() => huiDelete()">
                  <div class="clearHui">清空对话</div>
                </a-popconfirm>
              </div>
            </div>
          </div>
        </div>
        <global-footer />
      </div>
    </div>

    <member-model ref="modalMember" v-if="memberShow"></member-model>
  </div>
</template>
  
<script>
import ChatList from './ChatList'
import ChatHistory from './ChatHistory'
import { mapActions, mapGetters, mapState } from 'vuex'
import { getFileAccessHttpUrl, getAction } from '@/api/manage'
import { deleteAction } from '@/api/manage'
import MemberModel from './component/MemberModel' //付费跳转弹框
import GlobalFooter from '@/components/page/GlobalFooter'
import TechnicalList from './component/TechnicalList'
import { DialogueWebsocketMixin } from '@/mixins/DialogueWebsocketMixin'
export default {
  mixins: [DialogueWebsocketMixin],
  name: 'TechnicalModel',
  components: {
    ChatList,
    ChatHistory,
    MemberModel,
    GlobalFooter,
    TechnicalList,
  },
  data() {
    return {
      // 对话记录
      timeListStr: '',
      editTime: '',
      isActive: false,
      isMobileCont: false,
      timeListLeft: [],
      timeIndex: 0,
      generatedContentList: [],
      iconShow: true,
      sessionNoteData: [],
      // 对话记录结束
      memberShow: false,
      url: {
        list: '/sys/role/list',
      },
      listData: [],
      listData2: [
        { role: 'user', list: [{}] },
        { role: 'assistant', list: [{}] },
      ],
      intelligence: [{}],
      imgShow: '',
      imgShowBool: true,
      imgLoading: false,
      timer: null,
      wen: '',
      messages: [],
      bulletBox: false,
      chatListData: [],
      newMessage: '',
      copyNewMessage: '',
      newImage: '',
      oldScrollTop: 0,
      scrollFlag: true,
      Intervall: null,
      activeStep: '', // 默认选中的锚点的key值
      offsetTop: 0,
      serverHTML: '',
      ActiveKey: '1',
      textareaShow: true,
      screenWidth: '',
      screenHeight: '',
      ifQuery: true,
      menuTitleData: '',
      executeShow:false,
    }
  },
  render(h) {
    return h('div', {
      class: 'md',
      domProps: {
        innerHTML: this.text,
      },
    })
  },
  directives: {
    scroll: {
      inserted(el) {
        el.scrollIntoView()
      },
    },
  },
  computed: {
    isInputEmpty() {
      return this.newMessage.trim() === ''
    },
  },

  watch: {
    //监听路由地址的改变
    $route: {
      immediate: true,
      handler() {
        console.log('this.newMessage', this.$route.query.param)
      },
    },
  },

  mounted() {
    //查询聊天记录
    // this.workplaceTeams('', 'query')
    console.log('userInfo', this.userInfo())
    this.$nextTick(function () {
      const observer = new ResizeObserver((entries) => {
        for (let entry of entries) {
          // 获取标签的高度
          const height = entry.contentRect.height

          // 在这里可以对高度进行处理
          this.scrollToBottom()
          // console.log('标签的高度:', height)
        }
      })
      // 监听组件根元素的变化
      observer.observe(this.$refs.myElement)

      this.screenWidth = window.innerWidth
      this.screenHeight = window.innerHeight
      document.addEventListener('scroll', this.handleScroll, true)
    })
  },
  beforeDestroy() {
    //清除定时器
    this.getClearInterval()
  },
  methods: {
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    getClearInterval(){
      clearInterval(this.timer)
      this.timer = null
    },
    getAvatarTips() {
      return getFileAccessHttpUrl(this.menuTitleData.image)
    },
    huiDelete: function (id) {
      var that = this
      deleteAction('/skillmodel/api/clearChat', { typeId: this.timeIndex }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          this.workplaceTeams('', 'query')
        } else {
          that.$message.warning(res.message)
        }
      })
    },

    choseTime(item, index, type) {
      console.log('index', item, index)
      this.getClearInterval()
      if (type === 'delete') {
        this.timeIndex = index
      } else {
        if (this.timeIndex === index) {
          return
        }
        this.timeIndex = index
      }
      this.timeIndex = index
      this.ifQuery = true
      if (!this.iconShow) {
        this.iconShow = true
      }
      this.workplaceTeams('', 'query')
    },
    openMobileMode() {
      this.isActive = true
    },
    handleScroll(e) {
      var that = this
      const winHeight = e.target.scrollTop || document.documentElement.scrollTop
      // const divSetTop = that.$refs.claims.offsetTop
      // console.log(winHeight)
      if (winHeight >= 71) {
        that.isMobileCont = true
      } else {
        that.isMobileCont = false
      }
    },
 
    //停止生成
    StopGeneration() {
      this.getClearInterval()
      this.textareaShow = true
    },
    getAvatar() {
      return getFileAccessHttpUrl(this.avatar())
    },

    //滚动条保持最底部方法
    scrollToBottom() {
      this.$nextTick(() => {
        var container = this.$el.querySelector('.chat')
        container.scrollTop = container.scrollHeight
      })
    },
    //复制
    copyText(data) {
      const text = data // 要复制的文本内容
      const el = document.createElement('textarea')
      el.value = text
      document.body.appendChild(el)
      el.select()
      document.execCommand('copy')
      document.body.removeChild(el)
      this.$message.success('文本已复制')
    },

    //发出信息
    sendMessage() {
      this.initWebSocket()
      this.memberShow = false
      this.bulletBox = false
      this.ifQuery = true
      if (this.newMessage.trim() !== '') {
        this.textareaShow = false
        this.copyNewMessage = this.newMessage
        //我发出的
        this.messages.push({
          role: 'user',
          content: this.newMessage,
        })

        this.messages.push({
          role: 'assistant',
          content: '',
        })
        // this.output(this.newMessage)
        this.workplaceTeams(this.newMessage, 'submit')
        this.newMessage = ''
      }
    },

    changeCot(contData, index, titleData) {
      console.log('11111112132323232334444444444444444W', contData, index, titleData)
      this.close()
      this.messages = contData
      this.executeShow = false
      this.bulletBox = true
      setTimeout(() => { 
        if(this.messages.length !== 0){
          this.bulletBox = false
        }else{
          this.bulletBox = true
        }
       }, 1000) 

      this.timeIndex = index
      this.menuTitleData = titleData
      this.timeListStr = titleData.name
    },
    workplaceTeams(meg, type) {
      console.log('meg', meg)
      let obj = {
        content: meg,
        typeId: this.timeIndex,
      }
      var http = type === 'submit' ? this.$http.post('/skillmodel/api/ask', obj) : getAction('/skillmodel/api/list',obj)
      if(type === 'submit'){
        this.executeShow = true
      }
      http.then((res) => {
          console.log('res', res)
          this.executeShow = false
          this.textareaShow = true
          if (res.success) {
            if (type === 'query') {
              if (res.result.length === 0) {
                this.bulletBox = true
              } else {
                this.bulletBox = false
              }
            }
            if (res.code === 500) {
              this.$notification.warn({
                message: '提示',
                description: res.message,
                duration: 5,
              })
              this.characters(res.message)
              this.memberShow = true
            } else if (res.code === 501) {
              this.$notification.warn({
                message: '提示',
                description: res.message,
                duration: 5,
              })
              this.imgShowBool = true
              this.imgLoading = false
            } else {
              if (res.success && type === 'submit') {
                this.workplaceTeams('', 'query')
                // this.$refs.ChList.getSkillList()
                this.ifQuery = false
              } else {
                if (!this.ifQuery) {
                  //调用保持滚动条方法（这一步也可以在updated生命周期调用）
                  console.log('11111111111111111', this.messages)
                  let messages = res.result
                  // this.characters(messages[messages.length - 1].content)
                  this.$store.dispatch('userLimitList', { userId: this.userInfo().id })
                  this.ifQuery = false
                } else {
                  console.log('222222222222222222222222222')
                  this.messages = res.result
                  this.listData = res.result
                }
              }
            }
          } else {
            this.$notification.warn({
              message: '提示',
              description: res.message,
              duration: 5,
            })
            this.newMessage = this.copyNewMessage
            this.workplaceTeams('', 'query')
          }
        })
        .catch((error) => {
          console.log('error', error)
          // 处理请求失败
        })
    },
    websocketOnmessage: function (e) {
      console.log('-----接收消息-------', e.data)
      this.messages[this.messages.length - 1].content  += e.data
    },
    //琢个字显示
    characters(meg) {
      // this.data = this.textareaTo(meg)
      this.data = meg
      this.wen = ''
      //声明一个变量，用来监听要分割的长度
      var wenLen = 0
      this.timer = setInterval(() => {
        //取到data.content的第wenLen位
        this.wen = this.data.substr(0, wenLen)

        //wenLen大于data.content的长度，停止计时器
        if (wenLen < this.data.length) {
          this.textareaShow = false
          wenLen++
        } else {
          this.textareaShow = true
          this.getClearInterval()
          // return
        }
        // console.log(' this.wen', this.wen)
        this.$set(this.messages[this.messages.length - 1], 'content', this.wen)
      }, 50)
    },
    textareaTo(str) {
      let regs = new RegExp('\r', 'g')
      let reg = new RegExp('\n', 'g')
      let regSpace = new RegExp(' ', 'g')
      str = str.replace(reg, '<br/>')
      str = str.replace(regs, '<br/>')
      str = str.replace(regSpace, '&nbsp;')
      console.log('str', str)
      return str
    },
  },
}
</script>
  
  <style lang="less" scoped >
.reportList {
  padding: 0px;
  height: auto;
  .list-wrap {
    height: auto;
  }
  .li {
    padding: 12px 0px;
  }
}
.contAllThree {
  .AllOne {
    width: auto;
    border-radius: unset;
  }
}

.leftScroll {
  display: flex;
  flex-direction: column;
  height: 100%;
  justify-content: center;
  .contAllThree {
    display: unset;
    width: 48%;
    margin-right: 2%;
    margin-top: 0 !important;
    float: left;
    .AllOne {
      width: 100%;
    }

    // .AllOne:nth-child(2){
    //   margin-bottom: 0px;
    // }
  }
  .contAllThree:nth-child(1) {
    width: 60%;
  }
  .contAllThree:nth-child(2) {
    width: 38%;
    margin-right: 0px;
  }

  .topTile {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .left {
      font-size: 18px;
      font-weight: bold;
      color: #303030;
      .sml {
        font-size: 12px;
        font-weight: 400;
      }
    }
    .right {
      color: #999;
      img {
        width: 48px;
        height: 48px;
        border-radius: 50%;
      }
      .point {
        width: 24px;
        height: 24px;
        border-radius: unset;
      }
      &.more {
        cursor: pointer;
      }
    }
  }
  .bg {
    background: url(https://img.soogif.com/ee4bHgmX0MnX2LxyMK23u6x4MhA8xtl4.gif) no-repeat;
    background-attachment: fixed;
    background-size: 32% 23%;
    margin-bottom: 20px;
    height: 78px;
    .topTile .left {
      color: white;
    }
  }
  .content-item {
    margin-top: 10px;
    float: left;
    // height: 246px;
    overflow: hidden auto;
    .nav {
      color: white;
      font-weight: bold;
    }
    .write-item {
      padding: 10px;
      background-color: #f7f7f7;
      border-radius: 12px;
      box-shadow: 0 2px 8px #dddddd;
      width: 48%;
      float: left;
      cursor: pointer;
      overflow: hidden;
      margin: 2% 1% 0 1%;
      .title {
        color: black;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        /* autoprefixer: off*/
        -webkit-box-orient: vertical;
        /* autoprefixer: on*/
      }
      // &:nth-child(2n){
      //   margin-right: 0;
      // }
    }
  }
}
.chat-content {
  // background: #f0f2f5;
  float: right;
  padding: 10px;
  width: 100%;
}
.inputSend {
  float: left;
  width: 100%;
  // background: rgb(240, 242, 245);
}
.chatFunction {
  float: left;
  width: 100%;
  padding-top: 10px;
  position: relative;
}
.chat-atn {
  &.pop {
    color: #7a46fc;
    background: transparent;
    border-color: #7a46fc;
  }
  &.middle {
    height: 35px;
    padding: 0 23px;
    line-height: 35px;
    float: left;
    margin-right: 10px;
  }
}

.chat-messages {
  display: flex;
  align-items: center;
  margin: 12px 0 0 0;
  float: left;
  width: 100%;
  .chat-input {
    flex: 1;
    border: none;
    outline: none;
    resize: none;
    border-radius: 8px;
    height: 60px;
    line-height: 20px;
    padding: 10px 20px;
    background: #f7f7f7;
    margin-right: 10px;
  }
}

.chat-atn {
  border-radius: 4px;
  line-height: 1.5715;
  border: 1px solid transparent;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
  touch-action: manipulation;
  height: 32px;
  padding: 4px 15px;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.25);
  background: #f5f5f5;
  border-color: #d9d9d9;
  text-shadow: none;
  box-shadow: none;
  display: flex;
  align-items: center;
  justify-content: center;
  &.disable {
    cursor: not-allowed;
  }
  &.active {
    background: #7a46fc;
    border-color: #7a46fc;
    color: white;
    cursor: pointer;
  }
  .iconfont {
    margin-right: 5px;
  }
}
.chat-atn:hover {
  opacity: 0.7;
}
.chat {
  height: 450px;
  overflow-y: auto;
  background: url(../../assets/chatlogo1.png) no-repeat center;
  // background-attachment: fixed;
  background-size: 30%;
  float: left;
  width: 100%;
  .classify.right {
    width: 100%;
    text-align: right;
    display: block;
    .chatBox {
      width: 100%;
      display: flex;
      flex-direction: row-reverse;
    }
    .message {
      float: right;
    }
    img {
      margin-left: 10px;
    }
    .message-text {
      text-align: left;
      &.active {
        // background: linear-gradient(to bottom,blue,red);
        animation-name: blink;
        animation-duration: 5s;
      }
      @keyframes blink {
        0% {
          opacity: 1;
          color: red;
        }
        50% {
          opacity: 0.8;
          color: red;
        }
        70% {
          opacity: 0.6;
        }
        100% {
          opacity: 1;
        }
      }
    }
    .iconList {
      margin-right: 10px;
    }
  }
  .classify.left {
    .message {
      float: left;
    }
    .message-text {
      &.active {
        // background: linear-gradient(to bottom,blue,red);
        animation-name: blink;
        animation-duration: 5s;
      }
      @keyframes blink {
        0% {
          opacity: 1;
          color: red;
        }
        50% {
          opacity: 0.8;
          color: red;
        }
        70% {
          opacity: 0.6;
        }
        100% {
          opacity: 1;
        }
      }
    }

    img {
      margin-right: 10px;
    }
    .iconList {
      margin-left: 10px;
    }
  }
  .classify.base {
    .message-text {
      background-color: #938bff;
      color: white;
    }
  }
  .classify {
    margin-bottom: 20px;
    float: left;
    width: 100%;
    .chatBox {
      display: flex;
      align-items: center;
      .chat-header {
        float: left;
        img {
          width: 40px;
          height: 40px;
          object-fit: cover;
          border-radius: 50%;
          background: #ccc;
        }
      }
      .messages {
        max-width: 80%;
        float: left;
        .message {
        }
        &.bei-jin{
          max-width: 100%;
          width: 100%;
          .message{
            width: 100%;
            .message-text{
              background: linear-gradient(90deg, #f7f7f7 51%, #fff 91%);
            }
          }
        }
      }
    }
  }
  .message-text {
    background-color: #f7f7f7;
    padding: 10px 20px;
    border-radius: 8px;
    color: #24292f;
    font-size: 15px;
  }
}
.iconList {
  .iconDt {
    background: #f7f7f7;
    border-radius: 20px;
    height: 30px;
    width: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.ant-btn {
  border: unset;
  border-color: unset;
}
.loading {
  width: 22px;
  height: 22px;
  border: 2px solid #1890ff;
  border-top-color: transparent;
  border-radius: 50%;
  animation: rotate 0.75s linear infinite;
  float: right;
  margin-left: 4px;
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}

// AI绘画
.middle_con {
  padding: 20px 20px 0 20px;
  .middle_top {
    width: 100%;
    height: calc(100% - 60px);
    display: flex;
    align-items: center;
    justify-content: center;
    .main_image {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: flex-start;
      justify-content: center;
      padding: 20px;
      .image_container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        img {
          width: 200px;
          height: 200px;
          -o-object-fit: cover;
          object-fit: cover;
        }
        .title {
          color: #333;
          font-size: 16px;
          font-weight: 600;
        }
        .desc {
          color: #999;
          margin-top: 10px;
        }
      }
    }
  }
}
.main_sc {
  width: 320px;
  height: 320px;
  img {
    width: 100%;
    border: none;
  }
}

.main_sc .message-text {
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
}
.fixBoom {
  position: absolute;
  bottom: 7px;
  left: 50%;
  width: 100px;
  color: red;
  background: transparent;
  border: 1px solid red;
  text-align: center;
  border-radius: 4px;
  cursor: pointer;
}
.fixBoom:hover {
  opacity: 0.7;
}
.chatFunction {
  display: none !important;
}
.clearHui {
  font-size: 13px;
  margin-left: 5px;
  cursor: pointer;
}
.menuBox{
  width: 240px;
  background: white;
}



@media screen and (max-width: 767px) {

.asideBox{
  height: 100%;
  /deep/.posit{
    padding: 7px 7px 0px 7px;
  }
}  
.chatFunction {
    display: block !important;
  }
  .mobilChat {
    .AllOne {
      padding: 0;
    }
  }
  .leftScroll {
    .AllOne {
      padding: 5px;
    }
    .content-item {
      .write-item {
        width: 48%;
      }
    }
  }
}
</style>
  